package com.camera.simplewebcam;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

public class Main extends Activity {
	FrameLayout fl;
	CameraPreview cp;
	MySurfaceview ms;
	Button btn_takepicture;
	public Bitmap bmp=null;
	ImageView imageView;
	File project_file,testPersonPictures;
	String projectfile=Environment.getExternalStorageDirectory().getPath()+"/WuDi/";
	//保存被检测人图片的文件夹的路径
	String str_savePicturePath=Environment.getExternalStorageDirectory().getPath()+"/WuDi/Pictures/";
	@SuppressLint({ "NewApi", "InlinedApi", "ShowToast" }) @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		cp = new CameraPreview();
		ms=new MySurfaceview(this);
		setContentView(R.layout.activity_main);
		
		boolean sdCardExist = Environment.getExternalStorageState() .equals(Environment.MEDIA_MOUNTED); //判断sd卡是否存在 
		if (sdCardExist) {
			project_file=new File(projectfile);
			testPersonPictures=new File(str_savePicturePath);
			if (!project_file.exists()) {
				project_file.mkdirs();
			}
			if (!testPersonPictures.exists()) {
				testPersonPictures.mkdirs();
			}
		}
		
		imageView = new ImageView(this);  
		imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); 
		fl=(FrameLayout) findViewById(R.id.fl);
		btn_takepicture=(Button) findViewById(R.id.btn_takepicture);
		fl.addView(ms);
		Log.i("webcam", "start.");
		btn_takepicture.setOnClickListener(new OnClickListener() {
			
			@SuppressLint("ShowToast") @Override
			public void onClick(View arg0) {
//				fl.removeView(ms);
//				imageView.setImageBitmap(bmp);
//				fl.addView(imageView);
				    try {
				    	File file=new File(testPersonPictures, "555");
						file.createNewFile();
						FileOutputStream fos = new FileOutputStream(file);
				        BufferedOutputStream bos = new BufferedOutputStream(fos);
				        bmp.compress(Bitmap.CompressFormat.JPEG, 90, bos);
				        bos.flush();
				        bos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						Toast.makeText(Main.this, "保存失败", 0).show();
					}
			
			
			
			}
		});
	}
	
	class MySurfaceview extends SurfaceView implements SurfaceHolder.Callback, Runnable{
		static final String tag = "CameraPreview";
		private static final boolean DEBUG = true;
		protected Context context;
		private SurfaceHolder holder;
	    Thread mainLoop = null;
//		public Bitmap bmp=null;

		private boolean cameraExists=false;
		private boolean shouldStop=false;
		
		/// /dev/videox (x=cameraId+cameraBase) is used.prepareCamera
		// In some omap devices, system uses /dev/video[0-3],
		// so users must use /dev/video[4-].
		// In such a case, try cameraId=0 and cameraBase=4
		private int cameraId=2;
		private int cameraBase=0;
		//
		
		// This definition also exists in ImageProc.h.
		// Webcam must support the resolution 640x480 with YUYV format. 
		static final int IMG_WIDTH=640;
		static final int IMG_HEIGHT=480;

		// The following variables are used to draw camera images.
	    private int winWidth=0;
	    private int winHeight=0;
	    private Rect rect;
	    private int dw, dh;
	    private float rate;
	    
	    MySurfaceview(Context context) {
			super(context);
			this.context = context;
			if(DEBUG) Log.d("WebCam","CameraPreview constructed");
			setFocusable(true);
			
			holder = getHolder();
			holder.addCallback(this);
			holder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);	
		}
		
		int count = 0;
		
	    @Override
	    public void run() {
	        while (true && cameraExists) {
	        	Log.i(tag, "loop");
	        	//obtaining display area to draw a large image
	        	if(winWidth==0){
	        		winWidth=this.getWidth();
	        		winHeight=this.getHeight();

	        		if(winWidth*3/4<=winHeight){
	        			dw = 0;
	        			dh = (winHeight-winWidth*3/4)/2;
	        			rate = ((float)winWidth)/IMG_WIDTH;
	        			rect = new Rect(dw,dh,dw+winWidth-1,dh+winWidth*3/4-1);
	        		}else{
	        			dw = (winWidth-winHeight*4/3)/2;
	        			dh = 0;
	        			rate = ((float)winHeight)/IMG_HEIGHT;
	        			rect = new Rect(dw,dh,dw+winHeight*4/3 -1,dh+winHeight-1);
	        		}
	        	}
	        	
	        	// obtaining a camera image (pixel data are stored in an array in JNI).
	        	cp.processCamera();
	        	// camera image to bmp
	        	cp.pixeltobmp(bmp);
	        	
	            Canvas canvas = getHolder().lockCanvas();
	            if (canvas != null)
	            {
	            	// draw camera bmp on canvas
	            	canvas.drawBitmap(bmp,null,rect,null);

	            	getHolder().unlockCanvasAndPost(canvas);
	            }

	            if(shouldStop){
	            	shouldStop = false;  
	            	Log.i(tag, "break");
	            	break;
	            }	        
	        }
	        Log.i(tag, "线程退出12");
	    }

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			if(DEBUG) Log.d("WebCam", "surfaceCreated");
			if(bmp==null){
				bmp = Bitmap.createBitmap(IMG_WIDTH, IMG_HEIGHT, Bitmap.Config.ARGB_8888);
			}
			// /dev/videox (x=cameraId + cameraBase) is used
			int ret = cp.prepareCameraWithBase(cameraId, cameraBase);
			
			if(ret!=-1) cameraExists = true;
			
	        mainLoop = new Thread(this);
	        mainLoop.start();		
		}
		
		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
			if(DEBUG) Log.d("WebCam", "surfaceChanged");
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			if(DEBUG) Log.d("WebCam", "surfaceDestroyed");
			if(cameraExists){
				shouldStop = true;
				while(shouldStop){
					try{ 
						Thread.sleep(100); // wait for thread stopping
					}catch(Exception e){}
				}
			}
			cp.stopCamera();
		}   
	    
	    
	}
	
	
	
}
